﻿using HlElock.Api;
using HlElock.Api.Models;
using HlELock.Page.Views;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;

namespace HlELock.Page.ViewModels
{
    public class DoorLockWindowViewModel : BindableBase
    {
        private readonly RoomApiClient _apiClient;

        // 房间列表
        private ObservableCollection<RoomInfo> _rooms = new ObservableCollection<RoomInfo>();
        public ObservableCollection<RoomInfo> Rooms
        {
            get => _rooms;
            set => SetProperty(ref _rooms, value);
        }

        // 当前选中的房间
        private RoomInfo _selectedRoom;
        public RoomInfo SelectedRoom
        {
            get => _selectedRoom;
            set => SetProperty(ref _selectedRoom, value);
        }

        // 用于查询的表单数据
        private QueryRoomRequest _queryRoomForm = new QueryRoomRequest();
        public QueryRoomRequest QueryRoomForm
        {
            get => _queryRoomForm;
            set => SetProperty(ref _queryRoomForm, value);
        }

        // 命令
        public DelegateCommand OpenAddWindowCommand { get; } // 新增：打开添加窗口命令
        public DelegateCommand OpenEditWindowCommand { get; }
        public DelegateCommand DeleteRoomCommand { get; }
        public DelegateCommand LoadDataCommand { get; }

        public DoorLockWindowViewModel(RoomApiClient apiClient)
        {
            _apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));

            // 初始化命令
            OpenAddWindowCommand = new DelegateCommand(OpenAddWindow); // 新增：打开添加窗口命令
            OpenEditWindowCommand = new DelegateCommand(OpenEditWindow, () => SelectedRoom != null).ObservesProperty(() => SelectedRoom);
            DeleteRoomCommand = new DelegateCommand(async () => await DeleteRoomAsync(), () => SelectedRoom != null).ObservesProperty(() => SelectedRoom);
            LoadDataCommand = new DelegateCommand(async () => await LoadDataAsync()).ObservesProperty(() => QueryRoomForm);
            LoadDataAsync().Await();
        }

        private void OpenAddWindow()
        {
            // 创建添加窗口的 ViewModel，传递 API 客户端和一个回调函数
            var addViewModel = new AddRoomViewModel(_apiClient, (newRoom) =>
            {
                // 回调函数：将新添加的房间添加到主列表
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Rooms.Add(newRoom);
                });
            });

            // 创建并显示添加窗口
            var addWindow = new AddRoomWindow
            {
                DataContext = addViewModel
            };
            addWindow.ShowDialog();
        }

        private void OpenEditWindow()
        {
            if (SelectedRoom == null) return;

            var editRequest = new EditRoomRequest(
                flType: SelectedRoom.FlType,
                reason: "",
                tjDate: SelectedRoom.TjDate,
                extNum: SelectedRoom.ExtNum,
                operId: SelectedRoom.OperId,
                floor: SelectedRoom.Floor,
                build: SelectedRoom.Build,
                window: SelectedRoom.Window,
                prjCode: SelectedRoom.PrjCode,
                roomId: SelectedRoom.RoomId,
                face: SelectedRoom.Face,
                preId: SelectedRoom.PreId,
                sufid: SelectedRoom.SufId
            );

            var editViewModel = new EditRoomViewModel(_apiClient, editRequest, SelectedRoom);
            var editWindow = new EditRoomWindow
            {
                DataContext = editViewModel
            };
            editWindow.ShowDialog();
        }

        private async Task LoadDataAsync()
        {
            try
            {
                var rooms = await _apiClient.QueryRoomsAsync(QueryRoomForm);

                if (rooms != null)
                {
                    Rooms.Clear();
                    foreach (var room in rooms)
                    {
                        Rooms.Add(room);
                    }
                }
                else
                {
                    MessageBox.Show("查询房间失败，请检查网络或输入信息。", "失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool CanQuery()
        {
            return !string.IsNullOrWhiteSpace(QueryRoomForm.Build) ||
                   !string.IsNullOrWhiteSpace(QueryRoomForm.Floor) ||
                   !string.IsNullOrWhiteSpace(QueryRoomForm.RoomId) ||
                   !string.IsNullOrWhiteSpace(QueryRoomForm.PrjCode);
        }

        private async Task DeleteRoomAsync()
        {
            try
            {
                if (SelectedRoom == null) return;

                var deleteRequest = new DeleteRoomRequest(
                    build: SelectedRoom.Build,
                    floor: SelectedRoom.Floor,
                    roomId: SelectedRoom.RoomId,
                    prjCode: SelectedRoom.PrjCode,
                    operId: SelectedRoom.OperId,
                    tjDate: DateTime.Now.ToString("yyyy-MM-dd")
                );

                bool success = await _apiClient.DeleteRoomAsync(deleteRequest);
                if (success)
                {
                    Rooms.Remove(SelectedRoom);
                    SelectedRoom = null;
                    MessageBox.Show("房间删除成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("删除房间失败，请检查网络或输入信息。", "失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除房间时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}



